package com.example.chat.controller;


import com.example.chat.client.ChatWebClient;
import com.example.chat.entity.ChatRequestBody;
import com.example.chat.entity.ChatResponse;
import com.example.chat.properties.ChatProperties;
import com.example.vo.Result;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@RestController
@RequestMapping("/buyer/chat")
@Slf4j
public class ChatController {
    @Resource
    private ChatWebClient chatWebClient;
    @Resource
    private ChatProperties chatProperties;


    @GetMapping("/common/getToken")
    public Result<String> getToken(){
        HashMap<String, String> header = new HashMap<>();
        header.put("Content-Type","application/json");

        HashMap<String, String> params = new HashMap<>();
        params.put("client_id", chatProperties.getClientId());
        params.put("client_secret", chatProperties.getClientSecret());
        params.put("grant_type","client_credentials");

        String token = chatWebClient.getToken(header, params).getAccess_token();
        return Result.ok(token);
    }

    @PostMapping(value = "/common/chat",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> chat(@RequestParam(required = false) String access_token,@RequestBody ChatRequestBody chatRequestBody){
        log.info("chat{}",chatRequestBody);
        HashMap<String, String> header = new HashMap<>();
        header.put("Content-Type","application/json");
        HashMap<String, String> param = new HashMap<>();
        if(access_token == null){
            access_token = chatProperties.getAccessToken();
        }
        param.put("access_token",access_token);
        Flux<ChatResponse> responseFlux = chatWebClient.getChatMessage(header, param, chatRequestBody);
        return responseFlux.map(ChatResponse::getResult);
    }
}